package gui.batches.command;

import java.util.Iterator;
import java.util.List;

import hit.core.HomeInventoryTracker;
import hit.core.Item;
import hit.core.ProductContainer;

/**
 * A Command that handles the undo/redo of transferring Items to and from
 * a ProductContainer
 * */
public class TransferItemsCommand extends Command {
	private List<Item> itemsToTransfer;
	private ProductContainer start;
	private ProductContainer destination;
	
	/**
	 * Initialize the TransferItemsCommand
	 * @param itemsToTransfer the List of Items to transfer
	 * @param start the ProductContainer to transfer from
	 * @param destination the ProductContainer to transfer to
	 *  */
	public TransferItemsCommand(List<Item> itemsToTransfer, ProductContainer start, 
															ProductContainer destination) {
		this.itemsToTransfer = itemsToTransfer;
		this.start = start;
		this.destination = destination;
	}

	/**
	 * Transfer the Items to the destination ProductContainer in this Command
	 * */
	@Override
	public List<Item> Execute() {
		HomeInventoryTracker.Instance().GetItemFacade()
										.TransferItems(itemsToTransfer, destination);
		return itemsToTransfer;
	}
	
	/**
	 * Transfer the Items in this Command back to the ProductContainer they came from
	 * */
	@Override
	public List<Item> Undo() {
		HomeInventoryTracker.Instance().GetItemFacade().TransferItems(itemsToTransfer, start);
		
		//if the undo takes all the items of that product out of the destination, remove the
		//product from the destination
		Iterator<Item> i = HomeInventoryTracker.Instance().GetItemFacade().GetItemsByProduct(
				destination, itemsToTransfer.get(0).GetProduct());
		int count = 0;
		while (i.hasNext()) {
			i.next();
			count++;
		}
		if (count == 0) {
			HomeInventoryTracker.Instance().GetProductFacade().RemoveProductFromContainer(
					itemsToTransfer.get(0).GetProduct(), destination);
		}
		
		return itemsToTransfer;
	}
	
	/**
	 * Set the ProductContainer the Items in this Command came from
	 * @param start the starting ProductContainer
	 * */
	public void SetStart(ProductContainer start) {
		this.start = start;
	}
	
	/**
	 * Set the destination ProductContainer for this Command
	 * @param destination the new destination ProductContainer
	 * */
	public void SetDestination(ProductContainer destination) {
		this.destination = destination;
	}

}
